$(function () {
    let keyName = 'cid'
    let localdata = new LocalData('todolist14', keyName)
    let $todoList = $('#todolist')
    let $doneList = $('#donelist')
    let $todoCount = $('#todocount')
    let $doneCount = $('#donecount')
    class Item {
        constructor(title, done = false) {
            this.title = title
            this.done = done
        }
    }
    $('#title').on('keyup', function (e) {
        if (e.key === 'Enter') {
            let item = new Item(this.value)
            console.log(item)
            let newId = localdata.addData(item)
            item[keyName] = newId
            createLi(item)
            countNum()
        }
    })

    function createLi(itemdata) {
        if (itemdata.done) {
            $doneList.append(`<li>
            <input data-id="${itemdata[keyName]}" type="checkbox" checked/>
            <p>${itemdata.title}</p>
            <a data-id="${itemdata[keyName]}" href="javascript:;"></a>
         </li>`)
        } else {
            $todoList.append(`<li>
            <input data-id="${itemdata[keyName]}" type="checkbox" />
            <p>${itemdata.title}</p>
            <a data-id="${itemdata[keyName]}" href="javascript:;"></a>
         </li>`)
        }

    }
    localList()

    function localList() {
        let arrlist = localdata.readData()
        for (let item of arrlist) {
            createLi(item)
        }
        countNum()
    }
    $('#todolist,#donelist').on('click', 'li>a', function () {
        let $btndel = $(this)
        let id = $btndel.data('id')
        localdata.removeDataById(id)
        $btndel.parent().remove()
        countNum()
    })
    $('#todolist,#donelist').on('change', 'li>input', function () {
        let $chk = $(this)
        let itemId = $chk.data('id')
        if ($chk.prop('checked')) {
            $chk.parent().appendTo($doneList)
            changeDoneStatus(itemId, true)
        } else {
            $chk.parent().appendTo($todoList)
            changeDoneStatus(itemId, false)
        }
        countNum()
    })

    function changeDoneStatus(id, isdone) {
        let itemlist = localdata.readData()
        itemlist.forEach((ele, i) => {
            if (ele[keyName] === id) {
                ele.done = isdone
                return false
            }
        })
        localdata.saveData(itemlist)
    }

    function countNum() {
        let len1 = $todoList.children().length
        $todoCount.text(len1)
        let len2 = $doneList.children().length
        $doneCount.text(len2)
    }
})